package com.polaris.live.ui.live.fragment

import android.os.Bundle
import androidx.lifecycle.viewModelScope
import com.gyf.immersionbar.ImmersionBar
import com.polaris.live.common.manager.startCountdown
import com.polaris.live.common.mvvm.base2.BaseVbFragment
import com.polaris.live.common.network.parseState
import com.polaris.live.common.util.NavigationBarUtils
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.constant.LiveConst
import com.polaris.live.constant.UserConst
import com.polaris.live.databinding.FragmentCallBalanceBinding
import com.polaris.live.popup.GlobalPopupManager
import com.polaris.live.resp.back_resp.CallStartResp
import com.polaris.live.resp.go_resp.CallStartBean
import com.polaris.live.translation.R
import com.polaris.live.ui.live.widget.listener.OnBackPressedListener
import com.polaris.live.ui.live.widget.listener.OnCallAnswerListener
import com.polaris.live.viewmodel.live.CallAnswerViewModel

/**
 * 拨打余额不足
 *
 * @author Created by lucas on 2023/11/15 15:19
 * @since 1.0.0
 */
class CallBalanceFragment : BaseVbFragment<CallAnswerViewModel, FragmentCallBalanceBinding>(),
    OnBackPressedListener {

    private val mFromType by lazy {
        arguments?.getInt(LiveConst.Params.CALL_FROM_TYPE) ?: UserConst.From.UNKNOWN
    }
    private val mLastFromType by lazy {
        arguments?.getInt(LiveConst.Params.CALL_LAST_FROM_TYPE) ?: UserConst.LastFrom.UNKNOWN
    }
    private val mCallBean by lazy {
        arguments?.getParcelable<CallStartResp>(LiveConst.Params.CALL_BEAN)
            ?: throw IllegalArgumentException("callBean is null")
    }

    private var mOnCallAnswerListener: OnCallAnswerListener? = null

    private fun initImmersionBar() {
        ImmersionBar.with(this)
            .transparentBar()
            .titleBarMarginTop(mBinding.rlContent)
            .init()

        NavigationBarUtils.setNavigationHeight(mBinding.rlContent)
    }

    override fun initView(savedInstanceState: Bundle?) {
        initImmersionBar()

        mBinding.apply {
            vHeader.initData(pageType, mCallBean.call, mCallBean.answer)
        }
        mBinding.tvCalling.initView(viewLifecycleOwner)
        mBinding.tvCalling.showWaiting()
        initObserver()
        initListener()
        mViewModel.viewModelScope.startCountdown(20000, 1000, {}) {
            if (it == 0L) {
                mOnCallAnswerListener?.stopStream()
            }
        }

        var lastType: Boolean? = null
        GlobalPopupManager.showRechargePopup(
            requireContext(), mViewModel,
            onRechargeOk = {
                if (lastType != null) {
                    return@showRechargePopup
                }
                lastType = it
                if (it == true) {
                    mViewModel.compensationStart(
                        CallStartBean(
                            mFromType,
                            mLastFromType,
                            mCallBean.answer.userId,
                            mCallBean.call.userFrom
                        )
                    )
                } else if (it == false) {
                    mOnCallAnswerListener?.refuseCall()
                }
            }, isNeedBottom = true
        )
    }

    private fun initObserver() {
        mViewModel.compensationLiveData.observe(this) { state ->
            parseState(state, {
                mOnCallAnswerListener?.agreeCall(it)
            }, {
                ToastGravity.showGravity(it.message)
                mOnCallAnswerListener?.refuseCall()
            })
        }
        //关注主播
        mViewModel.followerLiveData.observe(this) { resultState ->
            parseState(resultState, {
                ToastGravity.showGravity(R.string.follower_succeed)
                mBinding.vHeader.updateFollowStatus(true)
            }, {
                ToastGravity.showGravity(it.errorMsg)
            })
        }
    }

    private fun initListener() {
        mBinding.apply {
            //点击关注
            vHeader.setOnFollowerClickListener {
                mViewModel.addFollower(mCallBean.answer.userId)
            }
        }
    }

    override fun onBackPressed(): Boolean {
        if (!isCreated() || activity?.isFinishing != false) {
            return true
        }

        mOnCallAnswerListener?.refuseCall()

        return true
    }

    fun setOnCallAnswerListener(l: OnCallAnswerListener) {
        this.mOnCallAnswerListener = l
    }

    companion object {

        private const val pageType = LiveConst.Page.CALL
    }
}